package cn.tedu.blog.server.service.impl;

import cn.tedu.blog.server.exception.ServiceException;
import cn.tedu.blog.server.mapper.FavoriteMapper;
import cn.tedu.blog.server.security.LoginPrincipal;
import cn.tedu.blog.server.service.IFavoritrService;
import cn.tedu.blog.server.utils.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class FavoritrServiceImpl implements IFavoritrService {

    @Autowired
    private FavoriteMapper favoriteMapper;

    @Override
    public int favoriteCountByUserId() {
        log.info("查询用户发表的文章数");
        // 从上下文中获得用户id
        Long userId = getUserId();
        int pagSize = favoriteMapper.favoriteCountByUserId(userId);
        return pagSize;
    }

    /*获取用户信息*/
    public LoginPrincipal getUserInfo(){

        UsernamePasswordAuthenticationToken authenticationToken=
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext()
                        .getAuthentication();
        if(authenticationToken==null){
            throw new ServiceException(ServiceCode.ERR_UNKNOWN,"没有登录信息");
        }
        // 如果authenticationToken不为空,获得其中的用户信息
        LoginPrincipal userInfo=(LoginPrincipal) authenticationToken.getPrincipal();
        // 返回登录用户信息
        return  userInfo;
    }
    /*获取用户id*/
    public Long getUserId(){
        return getUserInfo().getId();
    }
}
